<template>
  <div class="user">
    <div class="left">
      <div class="img">
        <img
          :src=" ruleForm.imgUrl ? 'http://localhost:3000'+ruleForm.imgUrl :oldSrc"
          alt=""
        >
      </div>
    </div>
    <div class="right">
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="编号">
          <el-input v-model="ruleForm.num"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="ruleForm.price"></el-input>
        </el-form-item>
        <el-form-item label="美食">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="ruleForm.txt"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="changeImg"
          >
            <img
              v-if="ruleForm.imgUrl"
              :src="ruleForm.imgUrl"
              class="avatar"
            >
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            ></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="updateUser('ruleForm')"
          >更新</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import request from '../util/axios.config'
export default {
  name: "Food",
  data() {
    return {
      ruleForm: {
        name: "",
        imgUrl: "",
        price: "",
        txt: "",
        num: "",
      },
      oldSrc:
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
    };
  },
  methods: {
    // changeImg(e) {
    //   this.ruleForm.imgUrl = URL.createObjectURL(e.raw);
    //   this.ruleForm.file = e.raw;
    // },
    // updateUser(formName) {
    //   // 要对象形式所以要实例化一下
    //   const params = new FormData();
    //   for (let i in this.ruleForm) {
    //     params.append(i, this.ruleForm[i]);
    //   }
    //   axios({
    //     url: "/api/user/addfood",
    //     method: "post",
    //     data: params,
    //     headers: { "Content-Type": "multipart/form-data" },
    //   }).then((result) => {
    //     console.log(result);
    //     this.$message({
    //       message: "更新成功",
    //       type: "success",
    //     });
    //     // console.log(result);
    //   });
    // },
    changeImg(e) {
      // console.log(p);
      // URL.createObjectURL生成一个本端口在线的图片地址
      this.ruleForm.imgUrl = URL.createObjectURL(e.raw);
      this.ruleForm.file = e.raw;
    },
    async calculateFileHash(file) {
      try {
        // 使用 file.arrayBuffer() 获取 ArrayBuffer，并等待它解析 
        const Buffer = await file.arrayBuffer();
        // 使用 SubtleCrypto.digest 计算 SHA-256 哈希 
        const hashBuffer = await crypto.subtle.digest("SHA-256", Buffer);
        // 将 ArrayBuffer 转换为可读的十六进制字符串  
        const hashArray = Array.from(new Uint8Array(hashBuffer)); 
        const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
        return hashHex
      } catch(err) {
        console.log(err);
      }
    },
    // 根据文件内容得到hash文件名
    async getFileName(){
      // 计算文件的hash值
      const fileHash = await this.calculateFileHash(this.ruleForm.file);
      // 获取文件扩展名
      const fileExtension = this.ruleForm.file.name.split(".").pop();
      // console.log(`${fileHash}.${fileExtension}`);
      return `${fileHash}.${fileExtension}`
    },

      // 点击上传
   async updateUser() {
      if(!this.ruleForm.file) {
        alert('你没选文件')
        return 
      }
      const filename = await this.getFileName()
      await this.uploadFile(this.ruleForm.file,filename)
   },

   // 切片上传文件
   async uploadFile(file,filename){
      // 把大文件进行切片
      const chunks = this.createFileChunks(file,filename)
      // console.log(chunks);
      // 实现并行上传
      const res = await chunks.map(({chunk,chunkFileName})=>{
        return request.post(`/upload/${filename}`,chunk,{
          headers:{//高五服务器请求体是一个二进制格式,是一个字节流
            'Content-Type':'application/octet-stream'
          },
          params:{
            chunkFileName
          }
        })
      })
      try{
        // 并行上传每个分片
        await Promise.all(res)
        // 等全部分片上传完了,会向服务器发送一个合并文件的请求
        await request.get(`merge/${filename}`)
        alert('文件上传成功')
      }catch(err){
          console.log(err);
      }
   },
   
   createFileChunks(file,filename){
      let chunks = [];
      // 计算一共要切成多少片
      let count = Math.ceil(file.size/(100*1024*1024))
      for (let i =0;i<count;i++){
        let chunk = file.slice(i*(100*1024*1024),(i+1)*(100*1024*1024))
        chunks.push({
          chunk,
          chunkFileName:`${filename}-${i}`
        })
      }
      return chunks
   }
  },
};
</script>

<style lang = "less" scoped>
.user {
  width: 40%;
  margin-top: 40px;
  margin-left: 40px;
  display: flex;
  .left {
    margin-right: 20px;
    text-align: center;
    width: 300px;
    height: 300px;
    background-color: #fafafa;
    .img {
      margin-top: 30px;
      margin-bottom: 20px;
      text-align: center;
      img {
        width: 150px;
        height: 150px;
        border-radius: 50%;
        overflow: auto;
      }
    }
  }
  .right {
    padding: 30px;
    width: 100%;
    background-color: #fafafa;

    .el-form-item {
      width: 100%;
      .el-button {
        margin-top: 10px;
      }
    }
  }
}
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
::v-deep .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>